package com.example.swimmingpool.controller.employee;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.swimmingpool.entity.employee.Employee;
import com.example.swimmingpool.qo.employee.EmployeeQo;
import com.example.swimmingpool.response.CommonResponse;
import com.example.swimmingpool.service.employee.EmployeeService;
import com.example.swimmingpool.vo.employee.EmployeeVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Resource
    private EmployeeService employeeService;

    @PostMapping("/list")
    public CommonResponse<IPage<Employee>> list(@RequestBody @Valid EmployeeQo qo) {
        var pages = employeeService.listEmployee(qo);
        return CommonResponse.success(pages);

    }

    @PostMapping("/add")
    public CommonResponse<Boolean> add(@RequestBody @Valid EmployeeVo vo) {
        var employee = BeanUtil.copyProperties(vo, Employee.class);
        var res = employeeService.save(employee);
        return CommonResponse.success(res);

    }

    @PostMapping("/delete")
    public CommonResponse<Boolean> delete(@RequestBody EmployeeVo vo) {
        var id = vo.getId();
        assert ObjectUtil.isNotNull(id) : "id不能为空!";
        var res = employeeService.removeById(id);
        return CommonResponse.success(res);
    }

    @PostMapping("/update")
    public CommonResponse<Boolean> update(@RequestBody EmployeeVo vo) {
        var employee = BeanUtil.copyProperties(vo, Employee.class);
        var res = employeeService.updateById(employee);
        return CommonResponse.success(res);
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        var data = employeeService.list();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("员工", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Employee.class).sheet("模板").doWrite(data);
    }

    @PostMapping("/names")
    public CommonResponse<List<Employee>> getNames(@RequestBody EmployeeVo vo) {
        var emloyeeList = employeeService
                .lambdaQuery()
                .select(Employee::getId,Employee::getName)
                .like(Employee::getWork, vo.getName())
                .list();
        return CommonResponse.success(emloyeeList);

    }

}
